package io.yuncheng.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.yuncheng.common.config.DictConfig;
import io.yuncheng.common.exception.RRException;
import io.yuncheng.common.utils.*;
import io.yuncheng.modules.job.entity.ScheduleJobEntity;
import io.yuncheng.modules.sys.entity.*;
import io.yuncheng.modules.sys.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.yuncheng.modules.sys.entity.*;
import io.yuncheng.modules.sys.service.*;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.pl.REGON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 提供外部接口不用登陆
 *
 * @author jared
 * @email 15721509625@163.com
 * @date 2020-10-29 18:50:09
 */
@RestController
@Api(tags = "外部接口")
@RequestMapping("sys/outer")
@Slf4j
public class OuterController {

    @Autowired
    private SubApplicationService subApplicationService;

    @Autowired
    private SysDeptService sysDeptService;

    @Resource
    private SubAppWarnLogService warnLogService;

    @Resource
    private DictConfig dictConfig;

    @Resource
    private SubAppLogService subAppLogService;

    @Resource
    private SubCascadePlatformLogService subCascadePlatformLogService;
    @Resource
    private SubCascadePlatformService subCascadePlatformService;
    @Value("${security.config.name}")
    private String name;
    @Value("${security.config.version}")
    private String version;
    /**
     * 列表
     */
    @GetMapping("/config/version")
    public R version(){
        return R.ok().put("data", version);
    }
    @GetMapping("/config/name")
    public R name(){
        return R.ok().put("data", name);
    }

    @ApiOperation("部门列表")
    @PostMapping("/dept-list")
    public R deptList() {
        return R.ok().put("data", sysDeptService.list());
    }
    @ApiOperation("部门信息")
    @PostMapping("/dept-info")
    public SysDeptEntity deptList(@RequestBody SysDeptEntity dept) {
        return sysDeptService.getOne(new QueryWrapper<SysDeptEntity>().setEntity(dept));
    }
    /**
     * 保存
     */
    @PostMapping("/dept-save")
    @ApiOperation("保存部门")
    public R deptSave(@RequestBody SysDeptEntity dept) {
        sysDeptService.save(dept);
        return R.ok();
    }
    @PostMapping("/dept-update")
    @ApiOperation("更新部门")
    public R deptUpdate(@RequestBody SysDeptEntity dept) {
        sysDeptService.updateById(dept);
        return R.ok();
    }
    @PostMapping("/app-list")
    @ApiOperation("应用列表")
    public R appList() {
        return R.ok().put("data", subApplicationService.list());
    }
    @ApiOperation("保存应用")
    @PostMapping("/app-save")
    public R appSave(@RequestBody SubApplicationEntity subApplication) {
        subApplicationService.save(subApplication);
        return  R.ok();
    }
    @ApiOperation("更新应用")
    @PostMapping("/app-update")
    public R appUpdate(@RequestBody SubApplicationEntity subApplication) {
        subApplicationService.updateById(subApplication);
        return  R.ok();
    }

    @ApiOperation("告警日志")
    @PostMapping("/agent-warning-log")
    public R warningLog(@RequestBody AgentWarningLogEntity warningLogEntity) {
        log.info("告警日志记录:",warningLogEntity);
        warnLogService.saveWarnLogOuter(warningLogEntity);
        return  R.ok();
    }

    @ApiOperation("告警日志批量")
    @PostMapping("/agent-warning-log-batch")
    public R warningLogBatch(@RequestBody List<AgentWarningLogEntity> agentArithmeticLogEntities) {
        for (AgentWarningLogEntity agentArithmeticLogEntity : agentArithmeticLogEntities) {
            warningLog(agentArithmeticLogEntity);
        }
        return  R.ok();
    }
    @ApiOperation("算法日志")
    @PostMapping("/agent-algorithm-log")
    public R algorithmLog(@RequestBody AgentArithmeticLogEntity agentArithmeticLogEntity) {
        log.info("算法日志:",agentArithmeticLogEntity);
        subAppLogService.saveOrUpdate(agentArithmeticLogEntity);
        return  R.ok();
    }

    @ApiOperation("算法日志批量")
    @PostMapping("/agent-algorithm-log-batch")
    public R algorithmLogBatch(@RequestBody List<AgentArithmeticLogEntity> agentArithmeticLogEntities) {
        log.info("算法日志:",agentArithmeticLogEntities);
        for (AgentArithmeticLogEntity agentArithmeticLogEntity : agentArithmeticLogEntities) {
            subAppLogService.saveOrUpdate(agentArithmeticLogEntity);
        }
        return  R.ok();
    }

    @Resource
    private SubAppLogCollectService subAppLogCollectService;

    /**
     *
     * @param agentArithmeticLogOuterEntity
     * @return
     */
    @ApiOperation("算法日志汇总接收")
    @PostMapping("/log-save-update")
    public R logCollect(@RequestBody SubAppLogCollectOuterEntity agentArithmeticLogOuterEntity) {
        SysDeptEntity sysDeptEntity = sysDeptService.queryByUnique(agentArithmeticLogOuterEntity.getRootDeptId() + "-" + agentArithmeticLogOuterEntity.getDeptId());
        SubApplicationEntity applicationEntity = subApplicationService.queryByDeptId(sysDeptEntity.getDeptId());
        agentArithmeticLogOuterEntity.setAppId(applicationEntity.getAppId());
        subAppLogCollectService.saveOrUpdateByAppIdLogDate(agentArithmeticLogOuterEntity);
        return  R.ok();
    }
    @Resource
    private SubAppAssessmentSplitService subAppAssessmentSplitService;
    /**
     *
     * @param
     * @return
     */
    @ApiOperation("密评登记数据接收")
    @PostMapping("/assessment-log-save-update")
    public R assessmentLog(@RequestBody SubAppAssessmentSplitOuterEntity appAssessmentSplitOuterEntity) {
        SysDeptEntity sysDeptEntity = sysDeptService.queryByUnique(appAssessmentSplitOuterEntity.getRootDeptId() + "-" + appAssessmentSplitOuterEntity.getDeptId());
        SubApplicationEntity applicationEntity = subApplicationService.queryByDeptId(sysDeptEntity.getDeptId());
        //构建创建数据并保存
        Boolean hasData = subAppAssessmentSplitService.notHasData(applicationEntity.getAppId(), appAssessmentSplitOuterEntity.getAssessmentDate());
        //有数据删除
        if(!hasData){
            List<SubAppAssessmentSplitEntity> list = subAppAssessmentSplitService.queryListByEntityAll(applicationEntity.getAppId(), appAssessmentSplitOuterEntity.getAssessmentDate());
            for (SubAppAssessmentSplitEntity appAssessmentSplitEntity : list) {
                subAppAssessmentSplitService.removeById(appAssessmentSplitEntity.getId());
            }
        }
        for (SubAppAssessmentSplitEntity splitEntity : appAssessmentSplitOuterEntity.getSplitEntities()) {
            splitEntity.setAppId(applicationEntity.getAppId());
            splitEntity.setId(null);
        }
        subAppAssessmentSplitService.saveBatch(appAssessmentSplitOuterEntity.getSplitEntities());
        return  R.ok();
    }
    @ApiOperation("级联接收")
    @PostMapping("/cascade-log-save")
    public R cascadeLog(@RequestBody SubCascadePlatformLogEntity agentArithmeticLogOuterEntity) {
        subCascadePlatformLogService.save(agentArithmeticLogOuterEntity);
        SubCascadePlatformEntity entity = subCascadePlatformService.queryByCascadeIdAndType(agentArithmeticLogOuterEntity.getCascadeId(), 1);
        entity.setCascadeStatus(3);
        subCascadePlatformService.updateById(entity);
        return  R.ok();
    }

    @ApiOperation("告警日志接收")
    @PostMapping("/warning-log-save-update")
    public R warningLong(@RequestBody OuterAppWarnLogList outerAppWarnLogList) {
        SysDeptEntity sysDeptEntity = sysDeptService.queryByUnique(outerAppWarnLogList.getRootDeptId() + "-" + outerAppWarnLogList.getDeptId());
        SubApplicationEntity applicationEntity = subApplicationService.queryByDeptId(sysDeptEntity.getDeptId());
        List<SubAppWarnLogEntity> agentWarningLogEntities = outerAppWarnLogList.getAgentWarningLogEntities();
        for (SubAppWarnLogEntity agentWarningLogEntity : agentWarningLogEntities) {
            QueryWrapper<SubAppWarnLogEntity> queryWrapper = new QueryWrapper<>();
            SubAppWarnLogEntity subAppWarnLogEntity = new SubAppWarnLogEntity();
            subAppWarnLogEntity.setTransactionId(agentWarningLogEntity.getTransactionId());
            subAppWarnLogEntity.setAppUniqueId(applicationEntity.getUniqueId());
            queryWrapper.setEntity(subAppWarnLogEntity);
            int count = warnLogService.count(queryWrapper);
            if(count > 0){
                continue;
            }
            SubAppWarnLogEntity saveEntity = new SubAppWarnLogEntity();
            saveEntity.setAppId(applicationEntity.getAppId());
            saveEntity.setAppUniqueId(agentWarningLogEntity.getAppUniqueId());
            saveEntity.setCreateDate(agentWarningLogEntity.getCreateDate());
            saveEntity.setAppWarnCode(agentWarningLogEntity.getAppWarnCode());
            saveEntity.setTransactionId(agentWarningLogEntity.getTransactionId());
            saveEntity.setAppStatus(agentWarningLogEntity.getAppStatus());
            saveEntity.setAppType(agentWarningLogEntity.getAppType());
            saveEntity.setArithId(agentWarningLogEntity.getArithId());
            saveEntity.setLogDate(agentWarningLogEntity.getLogDate());
            saveEntity.setLogMessage(agentWarningLogEntity.getLogMessage());
            warnLogService.save(saveEntity);

        }

        return  R.ok();
    }

    /**
     *  密码局省级数据
     */
    @PostMapping("/total-data")
    @ApiOperation("密码局省级数据")
    public R totalCity(@RequestBody SubApplicationEntity entity) {
        if(entity.getAppType() == null){
            entity.setAppType(1);
        }
        List<SysDeptEntity> sysDeptEntities = sysDeptService.queryListByType(Constant.DeptTypeEnum.PROVINCE.getValue());
        if(sysDeptEntities == null){
            throw  new RRException("请检查省级机构配置");
        }
        List<SubApplicationEntity> province = subApplicationService.queryConfirmListByRootDeptIdAndType(sysDeptEntities.get(0).getDeptId(), entity.getAppType());
        List<SysDeptEntity> cityDepts = sysDeptService.queryListByType(Constant.DeptTypeEnum.CITY.getValue());
        List<SubAppLogCollectVo> cityTotalList = new ArrayList<>();
        SubAppLogCollectObjectVo provinceVo = subAppLogCollectService.queryTotalByEntity(province);
        for (SysDeptEntity cityDept : cityDepts) {
            List<SubApplicationEntity> city = subApplicationService.queryConfirmListByRootDeptIdAndType(cityDept.getDeptId(), entity.getAppType());
            SubAppLogCollectObjectVo cityVo = subAppLogCollectService.queryTotalByEntity(city);
            SubAppLogCollectVo cityTotal = SubAppLogCollectVo.initBuildInterface(cityDept.getName());
            cityTotal.addTotalList(cityVo.getCallTotal());
            cityTotal.addTotalList(cityVo.getAppNum());
            cityTotal.addTotalList(cityVo.getLoginUser());
            cityTotal.addTotalList(cityVo.getInUseNum());
            cityTotal.addTotalList(cityVo.getEncryptionNum());
            cityTotalList.add(cityTotal.cleanMap());
            provinceVo.addTotal(cityVo);

        }
        List<SubAppLogCollectVo.VoEntity> subAppLogCollectVos = Arrays.asList(provinceVo.getAppNum().getTotal(), provinceVo.getInUseNum().getTotal(), provinceVo.getEncryptionNum().getTotal(), provinceVo.getLoginUser().getTotal(), provinceVo.getCallTotal().getTotal());
        return R.ok().put("data", subAppLogCollectVos);
    }
    /**
     *  密码局省级数据
     */
    @PostMapping("/city-total")
    @ApiOperation("密码局省级数据")
    public R totalCityAll(@RequestBody SubApplicationEntity entity) {
        if(entity.getAppType() == null){
            entity.setAppType(1);
        }
        List<SysDeptEntity> sysDeptEntities = sysDeptService.queryListByType(Constant.DeptTypeEnum.PROVINCE.getValue());
        if(sysDeptEntities == null){
            throw  new RRException("请检查省级机构配置");
        }
        List<SubApplicationEntity> province = subApplicationService.queryConfirmListByRootDeptIdAndType(sysDeptEntities.get(0).getDeptId(), entity.getAppType());
        List<SysDeptEntity> cityDepts = sysDeptService.queryListByType(Constant.DeptTypeEnum.CITY.getValue());
        List<SubAppLogCollectVo> cityTotalList = new ArrayList<>();
        SubAppLogCollectObjectVo provinceVo = subAppLogCollectService.queryTotalByEntity(province);
        for (SysDeptEntity cityDept : cityDepts) {
            List<SubApplicationEntity> city = subApplicationService.queryConfirmListByRootDeptIdAndType(cityDept.getDeptId(), entity.getAppType());
            SubAppLogCollectObjectVo cityVo = subAppLogCollectService.queryTotalByEntity(city);
            SubAppLogCollectVo cityTotal = SubAppLogCollectVo.initBuildInterface(cityDept.getName());
            cityTotal.addTotalList(cityVo.getCallTotal());
            cityTotal.addTotalList(cityVo.getAppNum());
            cityTotal.addTotalList(cityVo.getLoginUser());
            cityTotal.addTotalList(cityVo.getInUseNum());
            cityTotal.addTotalList(cityVo.getEncryptionNum());
            cityTotalList.add(cityTotal.cleanMap());
            provinceVo.addTotal(cityVo);

        }
        return R.ok().put("data", provinceVo.buildReturnVo()).put("city",cityTotalList);
    }
}
